package com.mrzhou.auth.support;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 集成认证的实体类,
 *  在IntegrationAuthenticationFilter过滤器中保存传入的参数及header信息
 */
@Getter
@Setter
@ToString
@Slf4j
public class IntegrationAuthenticationEntity {

    private String tenantId; // 租户id

    private String authType; //通过何种方式登录系统

    private String username; // 用户登录的姓名

    private String clientId; // 所属的客户端id

    private Map<String, String[]> authParameterMap; // 登录类型的参数

    private Map<String, String> authHeaderMap; // 请求中的header参数

    public String getAuthParameter(String paramName) {
        try{
            String[] values = this.authParameterMap.get(paramName);
            if(values != null && values.length > 0) {
                return values[0];
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("未从请求中的body获取[ {} ]的值", paramName);
        }
        return null;
    }

    public void setAuthParameter(String key, String[] values){
        if(this.authParameterMap == null) {
            this.authParameterMap = new HashMap<>();
        }
        this.authParameterMap.put(key, values);
    }

    public void setAuthParameterMap(HttpServletRequest request){
        this.authParameterMap = new HashMap<>(request.getParameterMap());
    }

    /**
     * 设置request中的请求头
     */
    public void setAuthHeaderMap(HttpServletRequest request){
        this.authHeaderMap = new HashMap<>();
        Enumeration<String> en  = request.getHeaderNames();
        while(en.hasMoreElements()) {
            String key = en.nextElement();
            String value = request.getHeader(key);
            this.authHeaderMap.put(key, value);
        }
    }

    /**
     * 获取指定header头中的参数
     */
    public String getAuthHeaderValue(String headerName) {
        return this.authHeaderMap.get(headerName);
    }

}
